<?php

namespace app\common\model;

use think\Loader;
use think\Model;
use think\Session;

class User extends Model
{
    //数据表名
    protected  $table = 'user';
    //数据表主键  复合主键使用数组定义  不设置则自动获取
    protected $pk = 'uid';

    /**
     * 登录
     */
    public function login($data){
        //1.手册搜索验证器  进行验证
        $validate = Loader::validate('User');
        if(!$validate->check($data)){
//            dump($validate->getError());
            return ['valid'=>0,'msg'=>$validate->getError()];
        }
        //2.对比用户名密码是否正确
        //实际上这里做一个查询的工作
        $userInfo = $this->where('username',$data['username'])->where('password',md5($data['password']))->find();
        if(!$userInfo){
            return ['valid'=>0,'msg'=>'用户名或密码错误'];
        }
        //3.存放session  登录成功
        session('admin.uid',$userInfo['uid']);
        session('admin.username',$userInfo['username']);
        return ['valid'=>1,'msg'=>'登录成功'];
    }
    //修改密码
    public function editPsw($data){
        //1.手册索搜验证器
        $validate = Loader::validate('UserEditPsw');
        if(!$validate->check($data)){
//            dump($validate->getError());
            return ['valid'=>0,'msg'=>$validate->getError()];
        }
        //查询数据库，比对原密码填写正确不正确
        $userInfo = $this->where('uid',session('admin.uid'))->where('password',md5($data['password']))->find();
        if(!$userInfo){
            return ['valid'=>0,'msg'=>'原密码填写不正确'];
        }
//        $row = $this->where('uid',session('admin.uid'))->update(['password'=>md5($data['new_password'])]);
        $bool = $this->save(['password'=>md5($data['new_password'])],[$this->pk=>session('admin.uid')]);
        if($bool){
            Session::delete('admin');
            return ['valid'=>1,'msg'=>'密码更新成功'];
        }
        return ['valid'=>0,'msg'=>'密码更新失败'];
    }
}





